package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 统计指定时间区间内的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //1. 计算从begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            //plusDays方法，获取指定天数后的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //将日期列表转换为以逗号分隔的字符串   数据格式由前端约定的
        String dateListString = StringUtils.join(dateList, ",");

        //2. 查询范围内每一天的营业额数据，与日期对应
        //查询营业额：订单表中，状态为 已完成 的订单的总金额
        List<Double> turnoverList = new ArrayList<>();

        dateList.forEach(date -> {  //遍历每一天，每一天查询一次
            //计算日期对应的起始时间， 当天起始时间 00:00:00 - 当天截止时间 23:59:59
            //将LocalDate类型的日期转为LocalDateTime类型
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 将当天日期和起始时间组合为LocalDateTime类型
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//LocalDate.MIN表示当天的起始时间，LocalDate.MAX表示当天的结束时间

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);

            //如果未查询到当天营业额，则设置为0
            if (turnover == null) {
                turnover = 0.0;
            }

            turnoverList.add(turnover);
        });

        //将turnoverList转为以逗号分隔的字符串   数据格式由前端约定的
        String turnoverListString = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(dateListString)
                .turnoverList(turnoverListString)
                .build();
    }


    /**
     * 获取用户数据
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1. 计算从begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            //plusDays方法，获取指定天数后的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //将日期列表转换为以逗号分隔的字符串   数据格式由前端约定的
        String dateListString = StringUtils.join(dateList, ",");

        //每天用户新增列表
        List<Integer> newUserList = new ArrayList<>();
        //每天用户总数列表
        List<Integer> totalUserList = new ArrayList<>();

        dateList.forEach(date -> {

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 将当天日期和起始时间组合为LocalDateTime类型
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//LocalDate.MIN表示当天的起始时间，LocalDate.MAX表示当天的结束时间

            Map map = new HashMap<>();
            map.put("end", endTime);  //先放end，先查询总用户数量，因为用的同一条sql，如果有begin就不符合查询所有用户的查询条件

            //查询当天总用户    总用户：查询user表中，create_time小于等于当前日期截至时间end的数量
            Integer totalUser = userMapper.countByMap(map);

            map.put("begin", beginTime); //加入begin查询条件
            //查询当天新增用户   新增用户：查询user表中，create_time在当前日期范围内的数据
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        });

        //将数组转为前端需要的字符串格式
        String newUserListString = StringUtils.join(newUserList, ",");
        String totalUserListString = StringUtils.join(totalUserList, ",");

        return UserReportVO
                .builder()
                .dateList(dateListString)
                .newUserList(newUserListString)
                .totalUserList(totalUserListString)
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //1. 计算从begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            //plusDays方法，获取指定天数后的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //将日期列表转换为以逗号分隔的字符串   数据格式由前端约定的
        String dateListString = StringUtils.join(dateList, ",");

        //订单总数列表
        List<Integer> totalOrderCountList = new ArrayList<>();
        //有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();

        dateList.forEach(date -> {

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 将当天日期和起始时间组合为LocalDateTime类型
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//LocalDate.MIN表示当天的起始时间，LocalDate.MAX表示当天的结束时间

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            //该天订单总数
            Integer totalOrderCount = orderMapper.countByMap(map);

            map.put("status", Orders.COMPLETED);  //加入status条件，查询有效订单数

            //该天有效订单数：  订单状态为已完成的订单数
            Integer validOrderCount = orderMapper.countByMap(map);

            totalOrderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        });

        //将数组转为前端需要的字符串格式
        String totalOrderCountListString = StringUtils.join(totalOrderCountList, ",");
        String validOrderCountListString = StringUtils.join(validOrderCountList, ",");

        //时间区间内的订单总数
        //通过stream流，将数组内的所有值加起来求和
        Integer totalOrderCountAll = totalOrderCountList.stream().reduce(Integer::sum).get();

        //时间区间内的有效订单数
        Integer validOrderCountAll = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率  有效订单数/订单总数
        Double orderCompletionRate = 0.0;
        if (totalOrderCountAll != 0) {
            //一定要先转为double类型后再运算，否则会忽略小数点后数字
            orderCompletionRate = validOrderCountAll.doubleValue() / totalOrderCountAll;
            // log.info("订单完成率：{}", orderCompletionRate);
        }

        return OrderReportVO
                .builder()
                .dateList(dateListString)
                .orderCountList(totalOrderCountListString)
                .validOrderCountList(validOrderCountListString)
                .totalOrderCount(totalOrderCountAll)
                .validOrderCount(validOrderCountAll)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        //将goodsSalesDTOList中每一项name和number分别存储到nameList和numberList中
        goodsSalesDTOList.forEach(goodsSalesDTO -> {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        });

        //将nameList和numberList转为前端需要的字符串格式
        String nameListString = StringUtils.join(nameList, ",");
        String numberListString = StringUtils.join(numberList, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameListString)
                .numberList(numberListString)
                .build();
    }

    /**
     * 导出最近30天运营数据excel报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库,获得运营数据, 最近30天 ,从30天前那一天 到 昨天
        LocalDate dateBegin = LocalDate.now().minusDays(30); //30天前
        LocalDate dateEnd = LocalDate.now().minusDays(1); //昨天

        //查询概览数据  30天的数据总和
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(
                LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI 将运营数据写入excel模板中
        //读取excel模板,从resources下读取,并转换为输入流对象
        InputStream input = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //通过输入流对象,创建excel对象,获取sheet页
            XSSFWorkbook excel = new XSSFWorkbook(input);

            XSSFSheet sheet = excel.getSheetAt(0);

            //写入概览数据
            //时间
            sheet.getRow(1).getCell(1).setCellValue("时间: " + dateBegin + "至" + dateEnd);
            //营业额
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            //有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //写入明细数据
            //这里行数确定，可以用for循环，方便指定 行和列下标   i: 0-29
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);  //每循环一次，日期多增加1天

                BusinessDataVO oneDayBusinessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //写入excel文件
                //日期列
                sheet.getRow(i+7).getCell(1).setCellValue(String.valueOf(date));
                //营业额列
                sheet.getRow(i+7).getCell(2).setCellValue(oneDayBusinessData.getTurnover());
                //有效订单列
                sheet.getRow(i+7).getCell(3).setCellValue(oneDayBusinessData.getValidOrderCount());
                //订单完成率列
                sheet.getRow(i+7).getCell(4).setCellValue(oneDayBusinessData.getOrderCompletionRate());
                //平均客单价列
                sheet.getRow(i+7).getCell(5).setCellValue(oneDayBusinessData.getUnitPrice());
                //新增用户数列
                sheet.getRow(i+7).getCell(6).setCellValue(oneDayBusinessData.getNewUsers());
            }

            //3. 通过输出流将excel文件写回浏览器客户端触发浏览器下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
